import json

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from datetime import datetime, timezone
from django.utils import timezone

from .models import QuestionManage, MyQuestion, Results, Questions

my_question = MyQuestion()


# Create your views here.
def index(request):
    if request.method == 'GET':
        content = {"msg": ''}
        return render(request, 'polls/index.html', content)
    if request.method == 'POST':
        visit_code = request.POST.get('visit_code')
        cur_vist_code = my_question.getVisitCode()
        if cur_vist_code is None:
            content = {"msg": '问卷已结束，请等待重新开始！'}
            return render(request, 'polls/index.html', content)
        print(cur_vist_code)
        print(visit_code)
        if str(visit_code) == str(cur_vist_code):
            return redirect(reverse("questions"))
        else:
            content = {"msg": '访问码不正确，请确认！'}
            return render(request, 'polls/index.html', content)


def praseIndex(value):
    if value is None:
        return None

    id, index = value.split('&')
    index_value = index.split(':')[1]

    return int(index_value)


def result_parse(post_data):
    questions_list = my_question.getQuestions()
    for question in questions_list:
        # print(question)
        question_id = question['id']
        db_question = Questions.objects.get(id=question_id)
        no = question['no']
        options_list = question['option_list']
        use_type = question['type']
        item_key = 'id:' + str(no) + '&'
        if item_key in post_data.keys():
            if use_type == 'radio':
                item_value = post_data[item_key]
                value = praseIndex(item_value) - 1
                db_question.results_set.create(answer=options_list[value], visit_code=my_question.getVisitCode(),
                                               commit_time=timezone.now())
            elif use_type == 'check':
                item_values = post_data.getlist(item_key)
                current_time = timezone.now()
                for item in item_values:
                    value = praseIndex(item) - 1
                    db_question.results_set.create(answer=options_list[value], visit_code=my_question.getVisitCode(),
                                                   commit_time=current_time)
            else:
                item_value = post_data[item_key]
                db_question.results_set.create(answer=item_value, visit_code=my_question.getVisitCode(),
                                               commit_time=timezone.now())
        else:
            print(item_key)
            db_question.results_set.create(answer="", visit_code=my_question.getVisitCode(),
                                           commit_time=timezone.now())


def question_api(request):
    if request.method == 'GET':
        if 'username' in request.GET and 'password' in request.GET:
            if User.objects.filter(username=request.GET['username']).exists():
                user = authenticate(username=request.GET['username'], password=request.GET['password'])
                if user is not None:
                    login(request, user)
                    result = {'cmd': 'ok'}
                else:
                    result = {'cmd': 'pwd_error'}
                return JsonResponse(result)
            else:
                result = {'cmd': 'no_username'}
                return JsonResponse(result)
        else:
            result = {'cmd': 'only supports tools'}
            return JsonResponse(result)
    else:
        data = json.loads(request.POST.get('data'))
        for question_item in data['questions_list']:
            q = Questions(question_text=question_item['question_text'],question_type=question_item['question_type'],question_must=question_item['question_must'])
            q.save()
            use_type = question_item['question_type']
            if use_type == 1 or use_type == 2:
                option_list = question_item['options_list']
                for option in option_list:
                    o = q.questionoptions_set.create(option_text=option)
            print(question_item)
        return JsonResponse({'cmd': 'ok'})


def visits_api(request):
    if request.method == 'GET':
        visited_list = []
        for item in QuestionManage.objects.all():
            visited_list.append(item.visit_code)
        data = {'data': visited_list,'questions':my_question.getAllQuestions(),'describe':my_question.getDescribe()}
        return JsonResponse(data)


def results_api(request):
    if request.method == 'GET':
        visit_code = request.GET['visit_code']
        print(visit_code)
        result_list = my_question.getResults(int(visit_code))
        data = {'data': result_list}
        return JsonResponse(data)


def questions(request):
    if request.method == 'POST':
        print(request.POST)
        result_parse(post_data=request.POST)
        return HttpResponse("OK reslutl.")
    else:
        content = {
            'question_list': my_question.getQuestions()
        }
        return render(request, 'polls/questions.html', content)


def manager_login(request):
    if request.method == 'GET':
        content = {"msg": ''}
        return render(request, 'polls/manage_login.html', content)
    if request.method == 'POST':
        user_name = request.POST['user_name']
        user_pwd = request.POST['user_pwd']

        if User.objects.filter(username=user_name).exists():
            print("user ok")
            user = authenticate(username=user_name, password=user_pwd)
            if user is not None:
                login(request, user)
                return redirect(reverse("manage"))
            else:
                content = {"msg": '用户名或密码错误，请重新输入！'}
                return render(request, 'polls/manage_login.html', content)
        else:
            print("user not exist")
            content = {"msg": '用户名和密码不存在，请重新输入！'}
            return render(request, 'polls/manage_login.html', content)


def login_or_logout(request):
    if request.method == 'GET':
        todo = request.GET.get('todo')
    else:
        todo = request.POST.get('todo')
    logout(request)
    return redirect(reverse('manager_login'))


def manage(request):
    if not request.user.is_authenticated:
        return redirect(reverse('manager_login'))
    questions = QuestionManage.objects.all()
    question_list = []
    if len(questions) != 0:
        for item in questions:
            temp = {
                'index': item.id,
                'start': item.start.strftime("%Y/%m/%d %H:%M:%S"),
                'finish': item.finish.strftime("%Y/%m/%d %H:%M:%S"),
                'visited_code': item.visit_code,
                'visited_count': item.visit_count,
                'commit_count': item.commit_count
            }
            question_list.append(temp)
    if my_question.getStatus() == 'stop':
        start_time = None
        visit_code = None
    else:
        start_time = my_question.getStartTime().strftime("%Y/%m/%d %H:%M:%S")
        visit_code = my_question.getVisitCode()
    content = {
        'question_list': question_list,
        'current_status': my_question.getStatus(),
        'start_time': start_time,
        'visit_code': visit_code
    }
    return render(request, 'polls/manage.html', content)


def manage_question(request):
    if not request.user.is_authenticated:
        return redirect(reverse('manager_login'))
    if request.method == 'GET':
        todo = request.GET.get('todo')
    else:
        todo = request.POST.get('todo')
    if todo == 'start':
        if my_question.getStatus() == "stop":
            my_question.startQuestion()
        return redirect(reverse('manage'))
    else:
        if my_question.getStatus() == "running":
            my_question.stopQuestion()
        return redirect(reverse('manage'))
